package com.mall.cms.controller;

import com.mall.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/minio")
public class CommonController {

    @Value("${upload.path}")
    private String savePath;

    @PostMapping("upload")
    public R upload(MultipartFile file, HttpServletRequest request){
        //获得文件原始文件名
        String originalFilename = file.getOriginalFilename();
        //获得文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构造新文件名
        String fileName = UUID.randomUUID().toString() + suffix;

        File dir = new File(savePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(savePath + fileName));
            return R.success("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }

    @PostMapping("/delete")
    public R delete(String objectName){

        File file = new File(savePath+objectName);
        boolean delete = file.delete();
        if (delete){
            return R.success("删除成功");
        }else {
            return R.error("删除失败");
        }
    }
}
